#include <iostream>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#include <vector>
#include <string.h>

#include "shmem_msg_fifo.h"

using namespace std;
static int count  = 0;

int main(int argc, char* argv[] )
{
    if (argc == 1)
    {
        cout<< "usage:"<<endl;
        cout<<"./sem 2"<<endl;
        cout<<"2 is sleep second"<<endl;
        return 0;
    }
    
    int sec = atoi(argv[1]);
    
    CShmem* sh  =new CShmem("monitor.shm",128);
    CSem *sem = new CSem("monitor.sem");
    pid_t pid = fork();
    // child
    if (pid == 0)
    {
        CShmemMsgFifo fifo(sh,sem);
        while (1)
        {
            char* pdata = NULL;
            unsigned int bytes = fifo.pop(&pdata);
            if (bytes > 0 && pdata != NULL)
            {
                cout<<"pop:"<<pdata<<endl;
                free(pdata);
            }
            cout<<"sleeping pop ..."<<endl;
            sleep(sec);
        }
    }
    else
    {
        CShmemMsgFifo fifo(sh,sem);
        char buf[] = "hello";
        while (1)
        {
            fifo.push(buf,strlen(buf));
            sleep(sec);
        }
    }
    return 0;
}



